import paramiko

class Parseoem:
    def __init__(self,sftp,oem):
        self.sftp = sftp
        self.oem = oem
        self.folder = self.getfolder()
        self.setlist = None

    def getfolder(self):
        return './log_rastrear/'
        #for new acp
        return './'

    def apontachunk(Self,chunklist,id):
        if not id is None:
            for i in range(len(chunklist)):
                if chunklist[i].id == id:
                    return chunklist[i]
            return None
        else:
            return chunklist[0]

    def getparam(self, param, id = None):
        file = self.getfile()
        chunklist = self.makechunklist(file)
        chunk = self.apontachunk(chunklist,id)
        if chunk is None:
            raise Exception('Indice \'%s\' nao encontrado' % id)
        if not param in chunk.values.keys():
            raise Exception('Parametro \'%s\' nao encontrado' % param)
        else:
            return chunk.values[param]

    def setparam(self,param, value, id = None):
        if self.setlist is None:
            file = self.getfile()
            self.setlist = self.makechunklist(file)
        chunk = self.apontachunk(self.setlist,id)
        if chunk is None:
            raise Exception('Indice \'%s\' nao encontrado' % id)
        if not param in chunk.values.keys():
            raise Exception('Parametro \'%s\' nao encontrado' % param)
        else:
            chunk.values[param] = value

    def setfile(self):
        fp = open('./OEMs/'+self.oem,'wb')
        listastr = map(str,self.setlist)
        listastr[-1] = listastr[-1][:-1]
        fp.writelines(listastr)
        fp.close()
        self.setlist = None
        self.sftp.put('./OEMs/'+self.oem,self.folder+self.oem)

            

    def makechunklist(self,lista):
        chunks = []
        lchunk = []
        for i in range(len(lista)):
            linha = lista[i].strip('\n').strip('\r')
            #gambi pro novo acp --- que tem um * no ultimo ;
            if linha[-1] == '*':
                linha = linha[:-1]
            if len(linha) > 2:
                if linha[0:2] == '//':
                    continue
            if linha == ';':
                pass
            elif linha == '*':
                #chunks.append(Chunk(lchunk))
                #del lchunk[:]
                #modificacao novo acp
                pass
            else:
                lchunk.append(linha)
            #modificacao novo acp
        chunks.append(Chunk(lchunk))
        return chunks

    def getfile(self):
        self.sftp.get(self.folder+self.oem,'./OEMs/'+self.oem)
        file = open('./OEMs/'+self.oem)
        lista = file.readlines()
        file.close()
        return lista

#------------------------------------------------------
class Chunk:
    def __init__(self,list):
        self.id = 0
        self.values = dict()
        self.ordlist = []
        self.makedict(list)

    def makedict(self,list):
        for linha in list:
            linha = linha.strip(';').split('=')
            self.values.update( { linha[0] : linha[1] } )
            self.ordlist.append(linha[0])
        self.id = self.values[self.ordlist[0]]

    def gettuples(self):
        l = []
        for param in self.ordlist:
            l.append((param,self.values[param]))
        return l

    def __str__(self,type=1):
        s = ''
        #modificacao pro novo acp
        #for param in self.ordlist:
        #    s += param + '=' + self.values[param] + ';\n'
        #s += '*\n'
        t = len(self.ordlist)
        for i in range(t):
            s += self.ordlist[i] + '=' + self.values[self.ordlist[i]]
            s += ';\n' if (i <> (t-1)) else '*\n'
        return s

class Eventchunk:
    def __init__(self,list):
        self.id = 0
        self.values = dict()
        self.makedict(list)

    def makedict(self,list):
        for linha in list:
            linha = linha.strip(';').split('=')


#------------------------------------------------------
if __name__=='__main__':
    ip = '192.168.2.250'
    porta = 22
    user = 'root'
    senha = '123456'
    t = paramiko.Transport((ip,porta))
    t.connect(username=user,password=senha)

    sftp = paramiko.SFTPClient.from_transport(t)
    oem = 'OEMOutputs.txt'
    parse = Parseoem(sftp,oem)

    
    try:
        parse.setparam('Behavior Oscillating','123','1')
        parse.setparam('Behavior Oscillating','456','2')
        parse.setparam('15 seconds in high state','100','1')
        parse.setparam('15 seconds in high state','200','2')
        parse.setparam('15 seconds in high state','300','3')
        parse.setparam('15 seconds in high state','400','4')
        parse.setparam('60 seconds in low state','100','1')
        parse.setparam('60 seconds in low state','200','2')
        parse.setparam('60 seconds in low state','300','3')
        parse.setparam('60 seconds in low state','400','4')
        parse.setfile()
        #print parse.getparam('15 seconds in high state','1')
    except Exception, e:
        print e

    t.close()
